package com.example.demo.shengcheng;

import java.util.Calendar;

public class scbz {

    private static final String[] TIANGAN = {"甲", "乙", "丙", "丁", "戊", "己", "庚", "辛", "壬", "癸"};
    private static final String[] DIZHI = {"子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"};

    public static void main(String[] args) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(1990, 3 - 1, 15, 23, 30); // 这里设置一个时间，示例为1990年3月15日23点30分
        String bazi = getBazi(calendar);
        System.out.println(bazi);
    }

    public static String getBazi(Calendar calendar) {
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        int hour = calendar.get(Calendar.HOUR_OF_DAY);

        int tianganIndex = (year - 4) % 10;
        int dizhiIndex = (year - 4) % 12;

        String tianganYear = TIANGAN[tianganIndex];
        String dizhiYear = DIZHI[dizhiIndex];

        String tianganMonth = TIANGAN[(tianganIndex * 2 + month - 2) % 10];
        String dizhiMonth = DIZHI[(month + 2) % 12];

        String tianganDay = getTianganDay(tianganIndex, dizhiIndex, year, month, day);
        String dizhiDay = DIZHI[(day - 1) % 12];

        String tianganHour = TIANGAN[(tianganIndex * 2 + hour / 2) % 10];
        String dizhiHour = DIZHI[hour / 2];

        return tianganYear + dizhiYear + tianganMonth + dizhiMonth + tianganDay + dizhiDay + tianganHour + dizhiHour;
    }

    private static String getTianganDay(int tianganIndex, int dizhiIndex, int year, int month, int day) {
        int daysFromStart = getDaysFromStart(year, month, day);
        int cyclePosition = (dizhiIndex * 12 + tianganIndex) % 60;
        int tianganPosition = (daysFromStart + cyclePosition - 3) % 10;
        return TIANGAN[tianganPosition];
    }

    private static int getDaysFromStart(int year, int month, int day) {
        int days = 0;
        for (int i = 4; i < year; i++) {
            days += 365;
            if (isLeapYear(i)) {
                days++;
            }
        }
        for (int i = 1; i < month; i++) {
            days += getDaysInMonth(year, i);
        }
        days += day - 1;
        return days;
    }

    private static boolean isLeapYear(int year) {
        return year % 400 == 0 || (year % 4 == 0 && year % 100 != 0);
    }

    private static int getDaysInMonth(int year, int month) {
        if (month == 2) {
            return isLeapYear(year) ? 29 : 28;
        } else if (month == 4 || month == 6 || month == 9 || month == 11) {
            return 30;
        } else {
            return 31;
        }
    }
}

